# -*- coding:utf-8 -*-

"""
=============================
this is a feibot product,
all rights reserved.
www.feibot.com
@author: Gu Tianyuan
@email: g@feibot.com
@time: 2023/3/16:10:21
@product: PyCharm
=============================
"""
import sys
from PyQt5.QtWidgets import QDialog, QApplication

import gtyConfig.systemConfig
from uiFiles import ui_logDialog

from gtyConfig import language,configFileHandler
import uiTools
import os
import glob
import time


class LogDialog(QDialog, ui_logDialog.Ui_logDialog):

    def __init__(self, mainPage, eventQ, parent=None):
        super(LogDialog, self).__init__(parent)
        self.setupUi(self)
        uiTools.centerAndSetIcon(self)
        self.eventQ = eventQ
        self.mainPage = mainPage
        self.configHandler = gtyConfig.configFileHandler.UserConfigHandler()
        self.deleteLogFileBeforeDays = self.configHandler.read('machine','deleteLogFileBeforeDays','int')
        self.uploadLogFilesBtn.setText(language.logDialog_upload)
        self.uploadRecentLogFilesBtn.setText(language.logDialog_uploadRecently)
        self.deleteLogFilesBtn.setText(language.logDialog_delete.replace('<d>',str(self.deleteLogFileBeforeDays)))
        self.uploadLogFilesBtn.clicked.connect(self.uploadAllLogFiles)
        self.uploadRecentLogFilesBtn.clicked.connect(self.uploadLogFilesRecently)
        self.deleteLogFilesBtn.clicked.connect(self.deleteAllLogFiles)
        self.setGeometry(-200, -200, self.width(), self.height())

        self.files = []
        self.recentFiles = []  # 最近一周的日志文件
        self.getLogFileInfo()
        self.getRecentLogFileInfo()
        self.returnBtn.clicked.connect(self.reject)
        self.mainPage.eventEngine.eventList["ui_uploadLogFileToServer"].connect(self.uploadLogFileResult)

    # 发生事件
    def sendEvent(self, task, eventName, eventData=None):
        if eventData is None:
            eventData = []
        e = [eventName, eventData]
        try:
            if task.upper() in self.eventQ.keys():
                self.eventQ[task.upper()].put(e)
        except Exception as e:
            print(e)

    # 上传全部日志文件
    def uploadAllLogFiles(self):
        self.sendEvent("IO","io_uploadAllLogFiles", self.files)

    # 上传最近一周的日志文件
    def uploadLogFilesRecently(self):
        self.sendEvent("IO", "io_uploadAllLogFiles", self.recentFiles)

    # 上传日志文件后的结果
    def uploadLogFileResult(self,result):
        if result[0] == "successful":
            self.label_info.setText(language.logDialog_uploadResultInfo+result[1])

    # 删除全部日志文件
    def deleteAllLogFiles(self):
        import datetime
        deletedCounter = 0
        for f in self.files:
            fileDate = f.split("-")[0][-10:]
            fileDateTime = datetime.datetime.strptime(fileDate, "%Y_%m_%d")
            now = datetime.datetime.now()
            dDays = (now - fileDateTime).days
            print(f,fileDate,dDays)
            if dDays > self.deleteLogFileBeforeDays:
                os.system('rm '+f)
                deletedCounter += 1
        self.label_info.setText(language.logDialog_logFileDeletedNum+str(deletedCounter))
        self.getLogFileInfo()

    # 获得日志文件信息
    def getLogFileInfo(self):
        logTotalSize = 0
        num = 0
        self.files = glob.glob(gtyConfig.systemConfig.getLogFilePath() + '/log*.txt')
        for f in self.files:
            num += 1
            logTotalSize += os.path.getsize(f)
        s = language.logDialog_logSizeInfo
        print(__file__, '日志文件信息：', num, logTotalSize)
        s = s.replace('<d>', str(num))
        s = s.replace('<s>', str(int(logTotalSize / 1024 / 1024 * 100) / 100) + "MB")
        self.label_states.setText(s)

    def getRecentLogFileInfo(self):
        logTotalSize = 0
        num = 0
        # 计算时间阈值（当前时间戳 - 7天）
        time_threshold = time.time() - 7 * 24 * 3600

        # 存储符合时间条件的文件列表
        recent_logs = []

        for f in self.files:
            # 检查文件修改时间
            if os.path.getmtime(f) >= time_threshold:
                recent_logs.append(f)  # 将文件加入列表
                num += 1
                logTotalSize += os.path.getsize(f)

        # 更新文件列表为最近一周的日志（可选）
        self.recentFiles = recent_logs

        # 格式化输出信息
        s = language.logDialog_recentLogSizeInfo
        print(__file__, '最近一周日志文件信息：', num, logTotalSize)
        s = s.replace('<d>', str(num))
        s = s.replace('<s>', f"{logTotalSize / 1024 / 1024:.2f}MB")
        str1 = self.label_states.text()
        self.label_states.setText(str1+'\n'+s)
